package org.ysu.shoeShopping.controller;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.ysu.shoeShopping.entity.Receives;
import org.ysu.shoeShopping.service.ReceivesService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收货地址表(Receives)表控制层
 *
 * @author makejava
 * @since 2025-09-13 17:11:08
 */
@RestController
@RequestMapping("address")
@CrossOrigin(origins = "*")
public class ReceivesController {
    /**
     * 服务对象
     */
    @Resource
    private ReceivesService receivesService;

    /**
     * 分页查询
     *
     * @param receives 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Receives>> queryByPage(Receives receives, PageRequest pageRequest) {
        return ResponseEntity.ok(this.receivesService.queryByPage(receives, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Receives> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.receivesService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param receives 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Receives> add(Receives receives) {
        return ResponseEntity.ok(this.receivesService.insert(receives));
    }

    /**
     * 编辑数据
     *
     * @param receives 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Receives> edit(Receives receives) {
        return ResponseEntity.ok(this.receivesService.update(receives));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.receivesService.deleteById(id));
    }

    /**
     * 根据用户ID查询收货地址列表
     * 前端请求路径: /api/address/findByUserId/{id}
     *
     * @param userId 用户ID
     * @return 用户的收货地址列表
     */
    @GetMapping("/findByUserId/{id}")
    public Map<String, Object> findByUserId(@PathVariable("id") Integer userId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 根据用户ID查询收货地址列表
            List<Receives> addressList = receivesService.findByUserId(userId);

            List<Map<String, Object>> addresses = new ArrayList<>();

            for (Receives receive : addressList) {
                Map<String, Object> address = new HashMap<>();
                address.put("id", receive.getRecid());                    // 地址ID
                address.put("province", receive.getRecprovince());        // 收货省份
                address.put("city", receive.getReccity());               // 收货城市
                address.put("district", receive.getRecdistrict());       // 收货地区
                address.put("street", receive.getRecstreet());           // 收货街道
                address.put("phone", receive.getRecmobile());               // 收货电话
                address.put("isDefault", receive.getRecisdefault() == 1); // 是否默认（转换为boolean）
                address.put("receiver", receive.getRecreceiver());       // 收货人

                addresses.add(address);
            }

            response.put("data", addresses);
            response.put("status", 200);
            response.put("message", "success");

        } catch (Exception e) {
            response.put("data", new ArrayList<>());
            response.put("status", 500);
            response.put("message", "查询地址失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 删除指定ID的地址信息
     * 前端请求路径: /api/address/delete/{id}
     *
     * @param addressId 地址ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteAddress(@PathVariable("id") Integer addressId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 删除指定ID的地址
            boolean deleteResult = receivesService.deleteById(addressId);

            if (deleteResult) {
                response.put("data", null);
                response.put("status", 200);
                response.put("message", "地址删除成功");
            } else {
                response.put("data", null);
                response.put("status", 404);
                response.put("message", "地址不存在或删除失败");
            }

        } catch (Exception e) {
            response.put("data", null);
            response.put("status", 500);
            response.put("message", "删除地址失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 新增地址信息
     * 前端请求路径: /address/add
     *
     * @param requestData 地址信息对象
     * @return 新增结果
     */
    @PostMapping("/add")
    public Map<String, Object> addAddress(@RequestBody Map<String, Object> requestData) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 从前端数据中提取字段并映射到实体对象
            Receives receives = new Receives();

            // 字段映射：前端字段名 -> 后端实体字段
            String province = (String) requestData.get("province");
            String city = (String) requestData.get("city");
            String district = (String) requestData.get("district");
            String street = (String) requestData.get("street");
            String phone = (String) requestData.get("phone");
            String receiver = (String) requestData.get("receiver");
            Object uidObj = requestData.get("uid");

            // 数据验证 - 检查必填字段
            if (province == null || province.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货省份不能为空");
                return response;
            }
            if (city == null || city.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货城市不能为空");
                return response;
            }
            if (district == null || district.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货地区不能为空");
                return response;
            }
            if (street == null || street.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货街道不能为空");
                return response;
            }
            if (phone == null || phone.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货手机不能为空");
                return response;
            }
            if (uidObj == null) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "用户ID不能为空");
                return response;
            }

            // 设置实体对象字段
            receives.setRecprovince(province);
            receives.setReccity(city);
            receives.setRecdistrict(district);
            receives.setRecstreet(street);
            receives.setRecmobile(phone);
            receives.setRecreceiver(receiver);

            // 处理用户ID
            Integer userId = null;
            if (uidObj instanceof Integer) {
                userId = (Integer) uidObj;
            } else if (uidObj instanceof String) {
                try {
                    userId = Integer.parseInt((String) uidObj);
                } catch (NumberFormatException e) {
                    response.put("data", null);
                    response.put("status", 400);
                    response.put("message", "用户ID格式不正确");
                    return response;
                }
            }
            receives.setUserId(userId);

            // 设置默认值
            receives.setRecisdefault(0); // 默认不是默认地址

            // 可选字段
            String postcode = (String) requestData.get("postcode");
            if (postcode != null) {
                receives.setRecpostcode(postcode);
            }


            // 新增地址信息
            Receives newAddress = receivesService.insert(receives);

            if (newAddress != null && newAddress.getRecid() != null) {
                // 构建返回的地址信息
                Map<String, Object> addressData = new HashMap<>();
                addressData.put("id", newAddress.getRecid());
                addressData.put("province", newAddress.getRecprovince());
                addressData.put("city", newAddress.getReccity());
                addressData.put("district", newAddress.getRecdistrict());
                addressData.put("street", newAddress.getRecstreet());
                addressData.put("phone", newAddress.getRecmobile());
                addressData.put("postcode", newAddress.getRecpostcode());
                addressData.put("isDefault", newAddress.getRecisdefault() == 1);
                addressData.put("receiver", newAddress.getRecreceiver());

                response.put("data", addressData);
                response.put("status", 200);
                response.put("message", "地址添加成功");
            } else {
                response.put("data", null);
                response.put("status", 500);
                response.put("message", "地址添加失败");
            }

        } catch (Exception e) {
            response.put("data", null);
            response.put("status", 500);
            response.put("message", "地址添加失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 修改地址信息
     * 前端请求路径: /address/update
     *
     * @param requestData 地址信息对象
     * @return 修改结果
     */
    @PutMapping("/update")
    public Map<String, Object> updateAddress(@RequestBody Map<String, Object> requestData) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 获取地址ID或用户ID
            Object idObj = requestData.get("id");
            Object uidObj = requestData.get("uid");

            Integer addressId = null;

            // 如果有地址ID，优先使用地址ID
            if (idObj != null) {
                if (idObj instanceof Integer) {
                    addressId = (Integer) idObj;
                } else if (idObj instanceof String) {
                    try {
                        addressId = Integer.parseInt((String) idObj);
                    } catch (NumberFormatException e) {
                        response.put("data", null);
                        response.put("status", 400);
                        response.put("message", "地址ID格式不正确");
                        return response;
                    }
                }
            }
            // 如果没有地址ID但有用户ID，查找用户的默认地址
            else if (uidObj != null) {
                Integer userId = null;
                if (uidObj instanceof Integer) {
                    userId = (Integer) uidObj;
                } else if (uidObj instanceof String) {
                    try {
                        userId = Integer.parseInt((String) uidObj);
                    } catch (NumberFormatException e) {
                        response.put("data", null);
                        response.put("status", 400);
                        response.put("message", "用户ID格式不正确");
                        return response;
                    }
                }

                // 查找用户的地址列表，找到默认地址或第一个地址
                List<Receives> userAddresses = receivesService.findByUserId(userId);
                if (userAddresses == null || userAddresses.isEmpty()) {
                    response.put("data", null);
                    response.put("status", 404);
                    response.put("message", "用户没有收货地址");
                    return response;
                }

                // 优先找默认地址，如果没有默认地址则使用第一个
                Receives targetAddress = userAddresses.stream()
                    .filter(addr -> addr.getRecisdefault() == 1)
                    .findFirst()
                    .orElse(userAddresses.get(0));

                addressId = targetAddress.getRecid();
            } else {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "地址ID或用户ID不能为空");
                return response;
            }

            // 检查地址是否存在
            Receives existingAddress = receivesService.queryById(addressId);
            if (existingAddress == null) {
                response.put("data", null);
                response.put("status", 404);
                response.put("message", "地址不存在");
                return response;
            }

            // 从前端数据中提取字段并映射到实体对象
            Receives receives = new Receives();
            receives.setRecid(addressId);

            // 字段映射：前端字段名 -> 后端实体字段
            String province = (String) requestData.get("province");
            String city = (String) requestData.get("city");
            String district = (String) requestData.get("district");
            String street = (String) requestData.get("street");
            String phone = (String) requestData.get("phone");
            String receiver = (String) requestData.get("receiver");

            // 数据验证 - 检查必填字段（如果字段有值的话）
            if (province != null && province.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货省份不能为空字符串");
                return response;
            }
            if (city != null && city.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货城市不能为空字符串");
                return response;
            }
            if (district != null && district.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货地区不能为空字符串");
                return response;
            }
            if (street != null && street.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货街道不能为空字符串");
                return response;
            }
            if (phone != null && phone.trim().isEmpty()) {
                response.put("data", null);
                response.put("status", 400);
                response.put("message", "收货手机不能为空字符串");
                return response;
            }

            // 设置实体对象字段（只设置前端传递的非null字段）
            if (province != null) receives.setRecprovince(province);
            if (city != null) receives.setReccity(city);
            if (district != null) receives.setRecdistrict(district);
            if (street != null) receives.setRecstreet(street);
            if (phone != null) receives.setRecmobile(phone);
            if (receiver != null) receives.setRecreceiver(receiver);

            // 可选字段
            String postcode = (String) requestData.get("postcode");
            if (postcode != null) {
                receives.setRecpostcode(postcode);
            }


            Object isDefaultObj = requestData.get("isDefault");
            if (isDefaultObj != null) {
                if (isDefaultObj instanceof Boolean) {
                    receives.setRecisdefault(((Boolean) isDefaultObj) ? 1 : 0);
                } else if (isDefaultObj instanceof Integer) {
                    receives.setRecisdefault((Integer) isDefaultObj);
                }
            }

            // 修改地址信息
            Receives updatedAddress = receivesService.update(receives);

            if (updatedAddress != null) {
                // 构建返回的地址信息
                Map<String, Object> addressData = new HashMap<>();
                addressData.put("id", updatedAddress.getRecid());
                addressData.put("province", updatedAddress.getRecprovince());
                addressData.put("city", updatedAddress.getReccity());
                addressData.put("district", updatedAddress.getRecdistrict());
                addressData.put("street", updatedAddress.getRecstreet());
                addressData.put("phone", updatedAddress.getRecmobile());
                addressData.put("postcode", updatedAddress.getRecpostcode());
                addressData.put("isDefault", updatedAddress.getRecisdefault() == 1);
                addressData.put("receiver", updatedAddress.getRecreceiver());

                response.put("data", addressData);
                response.put("status", 200);
                response.put("message", "地址修改成功");
            } else {
                response.put("data", null);
                response.put("status", 500);
                response.put("message", "地址修改失败");
            }

        } catch (Exception e) {
            response.put("data", null);
            response.put("status", 500);
            response.put("message", "地址修改失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 修改地址信息 (POST方法)
     * 前端请求路径: /address/update
     *
     * @param requestData 地址信息对象
     * @return 修改结果
     */
    @PostMapping("/update")
    public Map<String, Object> updateAddressPost(@RequestBody Map<String, Object> requestData) {
        return updateAddress(requestData);
    }

}

